//
//  KABMallHpVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/4/21.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallHpVC.h"
#import "ApiManager.h"
#import "XDAFNetworking.h"
#import "MBProgressHUD+XDPrompt.h"
#import <MJRefresh.h>
#import "KABModel.h"
#import "GlobalHeader.h"
#import <UIScrollView+EmptyDataSet.h>
#import "KABMallShopcartVC.h"
#import "KABMallClassifyVC.h"
#import "KABMallHpHeaderHFView.h"
#import "KABMallHpTCell.h"
#import "UrlToVC.h"

@interface KABMallHpVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (nonatomic, readonly) KABMallHomepage *mallHp;
@end

static NSString *const kHeaderViewId = @"KABMallHpHeaderHFView";
static NSString *const kReuseCellId = @"KABMallHpTCell";

@implementation KABMallHpVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"Kabu商城";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mall_classify"] style:UIBarButtonItemStylePlain target:self action:@selector(classifyBtnTapped:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mall_shop_cart"] style:UIBarButtonItemStylePlain target:self action:@selector(shopCartBarBtnTapped:)];
}

- (void)initSubViews {
    UINib *headerNib = [UINib nibWithNibName:kHeaderViewId bundle:nil];
    [self.tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:kHeaderViewId];
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 280.0;
    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionHeaderHeight = 45.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
//    self.tableView.mj_footer = self.mj_footer;
    
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"什么都没有喔" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.mallHp.homepage_list.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    KABMallHpItem *item = nil;
    if (section < self.mallHp.homepage_list.count) {
        item = self.mallHp.homepage_list[section];
    }
    return item.list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABMallHpTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.section < self.mallHp.homepage_list.count) {
        KABMallHpItem *hpItem = self.mallHp.homepage_list[indexPath.section];
        if (indexPath.row < hpItem.list.count) {
            [cell configViewWithHpListItem:hpItem.list[indexPath.row]];
        }
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    KABMallHpHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
    if (section < self.mallHp.homepage_list.count) {
        [view configViewWithHpItem:self.mallHp.homepage_list[section]];
    }
    return view;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 5.9;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    KABMallHpItem *hpItem = self.mallHp.homepage_list[indexPath.section];
    KABMallHpListItem *listItem = hpItem.list[indexPath.row];
    UIViewController *vc = [UrlToVC getVCfromUrlString:listItem.link_url];
    [self showViewController:vc sender:nil];
}

#pragma mark - event response
- (void)classifyBtnTapped:(UIBarButtonItem *)btnItem {
    KABMallClassifyVC *vc = [[KABMallClassifyVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)shopCartBarBtnTapped:(UIBarButtonItem *)barBtn {
    KABMallShopcartVC *vc = [[KABMallShopcartVC alloc] init];
    [self showViewController:vc sender:nil];
}

#pragma mark - private methods
- (void)jumpToExhDetailWithExhId:(NSInteger)exhId {
//    KABExhDetailVC *vc = [[KABExhDetailVC alloc] init];
//    vc.exhibition_id = exhId;
//    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
//    if (self.exhModel.totalLoad) {
//        [self.tableView.mj_footer endRefreshingWithNoMoreData];
//    } else {
//        [self.tableView.mj_footer resetNoMoreData];
//    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestCosplayListWithHeader:isHeader];
}

#pragma mark - network request
- (void)requestCosplayListWithHeader:(BOOL)isHeader {
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMallHomepage] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求商城首页返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] mallHomepageWithDictionary:responseObject];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求商城首页失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

- (KABMallHomepage *)mallHp {
    return [KABModel sharedInstance].mallHomepage;
}

@end
